extends Camera2D

## 目标缩放大小
var _target_zoom : float = 1

@export var can_wheel: bool = true
@export var can_key: bool = true
@export var can_drag:bool = true
@export var can_edge:bool = false


## 缩放倍数增量
@export var ZOOM_INCERMENT:float = 0.15
## 最大最小缩放倍数
@export var MAX_ZOOM: float = 0.2
@export var MIN_ZOOM: float = 1.2
## 缩放中
var _is_zoom_process : bool = false
## 缩放速率
@export var ZOOM_RATE: float = 4.0
@export var camera_margin: int = 10
@export var camera_speed: float = 200


## 镜头拖动
var _is_mouse_dragging: bool = false
var _prev_mouse_pos: Vector2

## 相机移动向量
var _camera_movement: Vector2


func _physics_process(delta: float) -> void:
	## 相机缩放
	if can_wheel and _is_zoom_process:
		zoom = lerp(zoom, _target_zoom * Vector2.ONE, delta * ZOOM_RATE)
		_is_zoom_process = not is_equal_approx(_target_zoom, zoom.x)
		
	## 鼠标拖动
	if can_drag and _is_mouse_dragging:
		_camera_movement = _prev_mouse_pos - get_global_mouse_position()
	
	## 指针位于屏幕边缘位置时，移动相机
	if can_edge:
		var _rect := get_viewport_rect()
		var _v := get_local_mouse_position() + _rect.size * 0.5
		if _rect.size.x - _v.x <= camera_margin:
			_camera_movement.x += camera_speed * delta
		if _rect.size.y - _v.y <= camera_margin:
			_camera_movement.y += camera_speed * delta
		if _v.x <= camera_margin:
			_camera_movement.x -= camera_speed * delta
		if _v.y <= camera_margin:
			_camera_movement.y -= camera_speed * delta
	
	
	## 键盘拖动摄像机
	if can_key:
		if Input.is_action_pressed("ui_up"):
			_camera_movement.y -= camera_speed * delta
		if Input.is_action_pressed("ui_down"):
			_camera_movement.y += camera_speed * delta
		if Input.is_action_pressed("ui_left"):
			_camera_movement.x -= camera_speed * delta
		if Input.is_action_pressed("ui_right"):
			_camera_movement.x += camera_speed * delta
	
	## 相机移动，记得乘上当前的缩放值zoom
	position += _camera_movement * zoom
	_camera_movement = Vector2.ZERO
	_prev_mouse_pos = get_global_mouse_position()
		

func _unhandled_input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_WHEEL_UP:
			_zoom_out()
		elif event.button_index == MOUSE_BUTTON_WHEEL_DOWN:
			_zoom_in()
		elif event.button_index == MOUSE_BUTTON_MASK_RIGHT:
			_is_mouse_dragging = true if event.pressed else false

## 摄像缩放
func _zoom_in() -> void:
	if not can_wheel: return
	_target_zoom = max(MAX_ZOOM, _target_zoom - ZOOM_INCERMENT)
	_is_zoom_process = true

func _zoom_out() -> void:
	if not can_wheel: return
	_target_zoom = min(MIN_ZOOM, _target_zoom + ZOOM_INCERMENT)
	_is_zoom_process = true
